/* eslint-disable camelcase */
/* eslint-disable @typescript-eslint/no-explicit-any */
// https://blog.csdn.net/weixin_71893751/article/details/132327831
// https://webpack.js.org/api/hot-module-replacement
// https://cloud.tencent.com/developer/article/1916404
import "@rspack/core/module";

import rspack = require("@rspack/core");
import tapable = require("tapable");

class Hook<T, R> extends tapable.Hook<T, R> {}

const hook = new Hook(["1"], "hookHook");

/// /////--------////////
const HotConfig = {
  OnInit: "hmrOnInit",
  OnStatus: "hmrOnStatus",
  OnCheck: "hmrOnCheck",
  OnDecline: "hmrOnDecline",
  OnDestroy: "hmrOnDestroy",
  AfterDestroy: "hmrAfterDestroy",
} as const;

type t = Rspack.HotEvent["type"];
/**
 * type HotEvent =
    | DeclinedEvent
    | UnacceptedEvent
    | AcceptedEvent
    | DisposedEvent
    | ErroredEvent;
 */
// `module.hot` in cjs
// `import.meta.webpackHot` in esm

function hmrModule(
  module_ref: any,
  _module: {
    hot?: Rspack.Hot;
  },
  Config = HotConfig,
) {
  if (_module.hot) {
    _module.hot.accept();
    if (module_ref.instance[Config.OnInit] && _module.hot.data) {
      module_ref.instance[Config.OnInit](_module.hot.data);
    }
    if (module_ref.instance[Config.OnStatus]) {
      // MODULE.hot.apply(function hmrOnStatus(status: any) {
      //   MODULE_REF.instance[MODULE_CONFIG['OnStatus']](status);
      // });
    }
    if (module_ref.instance[Config.OnCheck]) {
      // MODULE.hot.check(function hmrOnCheck(err: any, outdatedModules: any) {
      //   MODULE_REF.instance[MODULE_CONFIG['OnCheck']](err, outdatedModules);
      // });
    }
    if (module_ref.instance[Config.OnDecline]) {
      // MODULE.hot.decline(function hmrOnDecline(dependencies: any) {
      //   MODULE_REF.instance[MODULE_CONFIG['OnDecline']](dependencies);
      // });
    }
    _module.hot.dispose((store: any) => {
      if (module_ref.instance[Config.OnDestroy]) {
        module_ref.instance[Config.OnDestroy](store);
      }
      if (module_ref.instance[Config.AfterDestroy]) {
        module_ref.instance[Config.AfterDestroy](store);
      }
    });
  }
  return module_ref;
}

const mod = {
  hmrModule,
  MODULE_CONFIG: HotConfig,
};

export default mod;
